<template>
  <div>
    <el-input v-model="title" placeholder="请输入" class="w500" />
    <el-button type="primary" @click="handleAdd" @keyup.enter="handleAdd">
      新增
    </el-button>
    <div>
      <p v-for="(todo, index) in list" :key="index">
        <el-tag type="success" closable @close="handleRemove(index)">
          {{ todo }}
        </el-tag>
        <el-button
          type="primary"
          icon="el-icon-edit"
          circle
          size="mini"
          @click="handleEdit(index)"
        ></el-button>
      </p>
    </div>

    <el-dialog
      title="提示"
      v-model="dialogVisible"
      width="30%"
      :before-close="handleCloseDialog"
    >
      <span>编辑任务</span>
      <template #footer>
        <span class="dialog-footer">
          <el-input
            v-model="editForm.title"
            placeholder="请输入"
            class="w500"
          />
          <el-button @click="handleCloseDialog">取 消</el-button>
          <el-button type="primary" @click="saveUpdate">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, reactive, toRefs, ref } from 'vue'

export default defineComponent({
  name: 'TodoList',
  setup() {
    const list = ref<string[]>([])
    const editForm = reactive({
      title: '',
      index: ''
    })

    const state = reactive({
      title: '',
      list,
      dialogVisible: false
    })
    const handleAdd = () => {
      const { title, list } = state
      if (title) {
        state.list.push(title)
        state.title = ''
      }
    }
    const handleRemove = (index: number) => {
      state.list.splice(index, 1)
    }
    const handleCloseDialog = () => {
      state.dialogVisible = false
    }
    const handleEdit = (index: any) => {
      const { list } = state
      state.dialogVisible = true
      editForm.index = index
      editForm.title = list[index] || ''
    }
    const saveUpdate = () => {
      const { title, index } = editForm
      state.list.splice(index, 1, title)
      editForm.title = ''
      editForm.index = ''
      handleCloseDialog()
    }
    return {
      ...toRefs(state),
      editForm,
      handleAdd,
      handleRemove,
      handleCloseDialog,
      handleEdit,
      saveUpdate
    }
  }
})
</script>
<style lang="scss" scoped>
.w500 {
  width: 500px;
}
</style>
